package com.klasster.recruitmentPlatform.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.klasster.recruitmentPlatform.common.recommendation.CompanyRecommendationUtil;
import com.klasster.recruitmentPlatform.common.recommendation.JobRecommendationUtil;
import com.klasster.recruitmentPlatform.common.response.Result;
import com.klasster.recruitmentPlatform.common.response.ResultCode;
import com.klasster.recruitmentPlatform.common.util.ResumeSubmissionUtil;
import com.klasster.recruitmentPlatform.domain.dto.ResumeSubmissionDTO;
import com.klasster.recruitmentPlatform.domain.po.*;
import com.klasster.recruitmentPlatform.domain.vo.*;
import com.klasster.recruitmentPlatform.service.impl.*;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.LinkedList;

@RestController
@RequestMapping("/seeker")
@RequiredArgsConstructor
public class SeekerController {

    private final ProjectExperienceServiceImpl projectExperienceService;
    private final EducationExperienceServiceImpl educationExperienceService;
    private final WorkExperienceServiceImpl workExperienceService;
    private final JobIntentionServiceImpl jobIntentionService;
    private final CredentialServiceImpl credentialService;
    private final SeekerServiceImpl seekerService;
    private final JobServiceImpl jobService;
    private final CompanyServiceImpl companyService;
    private final RecruiterServiceImpl recruiterService;
    private final FollowingServiceImpl followingService;
    private final CollectionServiceImpl collectionService;
    private final UserServiceImpl userService;

    private final JobRecommendationUtil jobRecommendationUtil;
    private final CompanyRecommendationUtil recommendationUtil;
    private final ResumeSubmissionUtil resumeSubmissionUtil;


    /**
     * 查询求职者简历
     */
    @GetMapping("/getResume/{seeker_id}")
    public Result getResume(@PathVariable Long seeker_id) {
        Seeker seeker = seekerService.getById(seeker_id);
        List<ProjectExperience> projectExperienceList = projectExperienceService.getBySeekerID(seeker_id);
        List<EducationExperience> educationExperienceList = educationExperienceService.getBySeekerID(seeker_id);
        List<WorkExperience> workExperienceList = workExperienceService.getBySeekerID(seeker_id);
        List<JobIntention> jobIntentionList = jobIntentionService.getBySeekerID(seeker_id);
        User user = userService.getById(seeker_id);
        ResumeVO resume = BeanUtil.copyProperties(seeker,ResumeVO.class);
        resume.setAvatar_url(user.getAvatar_url());
        resume.setProject_experiences(projectExperienceList);
        resume.setEducation_experiences(educationExperienceList);
        resume.setWork_experiences(workExperienceList);
        resume.setJob_intentions(jobIntentionList);
        return Result.success(ResultCode.SEEKER_GET_RESUME,resume);
    }


    @GetMapping("/getSeeker/{seeker_id}")
    public Result getSeeker(@PathVariable Long seeker_id) {
        Seeker seeker = seekerService.getById(seeker_id);
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,seeker);
    }

    @Transactional
    @PutMapping("/updateSeeker")
    public Result updateSeeker(@RequestBody Seeker seeker) {
        return Result.success(ResultCode.SEEKER_SAVE_SUCCESS,seekerService.saveOrUpdate(seeker));
    }

//    @Transactional
//    @DeleteMapping("/deleteSeeker")
//    public Result deleteSeeker(@RequestBody Seeker seeker) {
//        return Result.success(ResultCode.SEEKER_SAVE_SUCCESS,seekerService.removeById(seeker));
//    }

    @GetMapping("/getProjectExperience/{seeker_id}")
    public Result getProjectExperience(@PathVariable Long seeker_id) {
        List<ProjectExperience> projectExperienceList = projectExperienceService.getBySeekerID(seeker_id);
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,projectExperienceList);
    }

    @Transactional
    @PostMapping("/saveProjectExperience")
    public Result saveProjectExperience(@RequestBody ProjectExperience projectExperience) {
        return Result.success(ResultCode.SEEKER_SAVE_SUCCESS,projectExperienceService.saveOrUpdate(projectExperience));
    }

    @Transactional
    @DeleteMapping("/deleteProjectExperience")
    public Result deleteProjectExperience(@RequestBody ProjectExperience projectExperience) {
        return Result.success(ResultCode.SEEKER_SAVE_SUCCESS,projectExperienceService.removeById(projectExperience));
    }


    @GetMapping("/getEducationExperience/{seeker_id}")
    public Result getEducationExperience(@PathVariable Long seeker_id) {
        List<EducationExperience> educationExperienceList = educationExperienceService.getBySeekerID(seeker_id);
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,educationExperienceList);
    }

    @Transactional
    @PostMapping("/saveEducationExperience")
    public Result saveEducationExperience(@RequestBody EducationExperience educationExperience) {
        System.out.println(educationExperience);
        return Result.success(ResultCode.SEEKER_SAVE_SUCCESS,educationExperienceService.saveOrUpdate(educationExperience));
    }

    @Transactional
    @DeleteMapping("/deleteEducationExperience")
    public Result deleteEducationExperience(@RequestBody EducationExperience educationExperience) {
        return Result.success(ResultCode.SEEKER_SAVE_SUCCESS,educationExperienceService.removeById(educationExperience));
    }


    @GetMapping("/getWorkExperience/{seeker_id}")
    public Result getWorkExperience(@PathVariable Long seeker_id) {
        List<WorkExperience> workExperienceList = workExperienceService.getBySeekerID(seeker_id);
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,workExperienceList);
    }

    @Transactional
    @PostMapping("/saveWorkExperience")
    public Result saveWorkExperience(@RequestBody WorkExperience workExperience) {
        return Result.success(ResultCode.SEEKER_SAVE_SUCCESS,workExperienceService.saveOrUpdate(workExperience));
    }

    @Transactional
    @DeleteMapping("/deleteWorkExperience")
    public Result deleteWorkExperience(@RequestBody WorkExperience workExperience) {
        return Result.success(ResultCode.SEEKER_SAVE_SUCCESS,workExperienceService.removeById(workExperience));
    }


    @GetMapping("/getJobIntention/{seeker_id}")
    public Result getJobIntention(@PathVariable Long seeker_id) {
        List<JobIntention> jobIntentionList = jobIntentionService.getBySeekerID(seeker_id);
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,jobIntentionList);
    }

    @Transactional
    @PostMapping("/saveJobIntention")
    public Result saveJobIntention(@RequestBody JobIntention jobIntention) {
        return Result.success(ResultCode.SEEKER_SAVE_SUCCESS,jobIntentionService.saveOrUpdate(jobIntention));
    }

    @Transactional
    @DeleteMapping("/deleteJobIntention")
    public Result deleteJobIntention(@RequestBody JobIntention jobIntention) {
        return Result.success(ResultCode.SEEKER_SAVE_SUCCESS,jobIntentionService.removeById(jobIntention));
    }

    @Transactional
    @PutMapping("/updateCredential")
    public Result updateCredential(@RequestBody Credential credential) {
        return Result.success(ResultCode.SEEKER_SAVE_SUCCESS,credentialService.saveOrUpdate(credential));
    }

    @Transactional
    @DeleteMapping("/deleteCredential")
    public Result deleteCredential(@RequestBody Credential credential) {
        return Result.success(ResultCode.SEEKER_SAVE_SUCCESS,credentialService.removeById(credential));
    }

    /**
     * 根据求职者id和求职意向获取推荐职位列表
     */
    @GetMapping("/getRecommendJobs/{seeker_id}")
    public Result getRecommendJobs(@PathVariable Long seeker_id, @RequestParam int amount) {
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,jobRecommendationUtil.getRecommendJobs(seeker_id,amount));
    }

    /**
     * 获取推荐职位列表（未登录的游客使用）
     */
    @GetMapping("/getCommonRecommendJobs")
    public Result getCommonRecommendJobs(@RequestParam int amount) {
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,jobRecommendationUtil.getCommonRecommendJobs(amount));
    }

    /**
     * 根据求职者id和求职意向获取推荐公司列表
     */
    @GetMapping("/getRecommendCompanies/{seeker_id}")
    public Result getRecommendCompanies(@PathVariable Long seeker_id, @RequestParam int amount) {
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,recommendationUtil.getRecommendCompanies(seeker_id,amount));
    }

    /**
     * 获取推荐公司列表（未登录的游客使用）
     */
    @GetMapping("/getCommonRecommendCompanies")
    public Result getCommonRecommendCompanies(@RequestParam int amount) {
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,recommendationUtil.getCommonRecommendCompanies(amount));
    }

    /**
     * 获取职位详情
     */
    @GetMapping("/getJobDetail/{job_id}")
    public Result getJobDetail(@PathVariable Long job_id) {
        Job job = jobService.getById(job_id);
        Recruiter recruiter = recruiterService.getById(job.getRecruiter_id());
        Company company = companyService.getById(job.getCompany_id());
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,new JobDetailVO(job,recruiter,company));
    }

    /**
     * 获取公司详情
     */
    @GetMapping("/getCompanyDetail/{company_id}")
    public Result getCompanyDetail(@PathVariable Long company_id, @RequestParam Integer job_count) {
        Company company = companyService.getById(company_id);
        QueryWrapper<Job> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",company_id).eq("state",1);
        if(job_count>0) {
            queryWrapper.last("limit "+job_count);
        }
        List<Job> list = jobService.list(queryWrapper);
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,new CompanyDetailVO(company, BeanUtil.copyToList(list,JobBriefVO.class)));
    }

    /**
     * 收藏职位
     */
    @Transactional
    @PostMapping("/collectJob")
    public Result collectJob(@RequestParam Long seeker_id, @RequestParam Long job_id) {
        // 先判断是否已经收藏过
        QueryWrapper<Collection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seeker_id",seeker_id).eq("job_id",job_id).eq("state",1);
        if(collectionService.getOne(queryWrapper)!=null) {
            return Result.error(ResultCode.SEEKER_COLLECTION_FAIL,false);
        }
        Collection collection = new Collection();
        collection.setSeeker_id(seeker_id);
        collection.setState(1);
        collection.setJob_id(job_id);
        return Result.success(ResultCode.SEEKER_COLLECTION_SUCCESS,collectionService.save(collection));
    }

    /**
     * 获取已收藏职位列表
     */
    @GetMapping("/getCollection/{seeker_id}")
    public Result getCollection(@PathVariable Long seeker_id) {
        QueryWrapper<Collection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seeker_id",seeker_id).eq("state",1);
        List<Collection> collections = collectionService.list(queryWrapper);
        List<JobHomeVO> jobs = new LinkedList<>();
        collections.forEach(e -> {
            Long job_id = e.getJob_id();
            QueryWrapper<Job> jobQueryWrapper = new QueryWrapper<>();
            jobQueryWrapper.eq("job_id",job_id).eq("state",1);
            Job job = jobService.getOne(jobQueryWrapper);
            if(job!=null) {
                JobHomeVO jobHomeVO = BeanUtil.copyProperties(job,JobHomeVO.class);
                Company company = companyService.getById(jobHomeVO.getCompany_id());
                jobHomeVO.setCompany_icon(company.getCompany_icon());
                jobHomeVO.setCompany_name(company.getCompany_name());
                jobHomeVO.setIndustry_code(company.getIndustry_code());
                jobHomeVO.setSize(company.getSize());
                jobs.add(jobHomeVO);
            }
        });
        return Result.success(ResultCode.SEEKER_COLLECTION_SUCCESS,jobs);
    }

    /**
     * 撤销收藏职位
     */
    @Transactional
    @PutMapping("/cancelCollection")
    public Result cancelCollection(@RequestParam Long seeker_id, @RequestParam Long job_id) {
        UpdateWrapper<Collection> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("seeker_id",seeker_id).eq("job_id",job_id).eq("state",1);
        updateWrapper.set("state",0);
        return Result.success(ResultCode.SEEKER_COLLECTION_SUCCESS,collectionService.update(updateWrapper));
    }

    /**
     * 判断是否已收藏职位
     */
    @GetMapping("/hasCollectedJob")
    public Result hasCollectedJob(@RequestParam Long seeker_id, @RequestParam Long job_id) {
        QueryWrapper<Collection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seeker_id",seeker_id).eq("job_id",job_id).eq("state",1);
        return Result.success(ResultCode.SEEKER_COLLECTION_SUCCESS,collectionService.getOne(queryWrapper)!=null);
    }


    /**
     * 关注企业
     */
    @Transactional
    @PostMapping("/followCompany")
    public Result followCompany(@RequestParam Long seeker_id, @RequestParam Long company_id) {
        // 先判断是否已经关注过
        QueryWrapper<Following> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seeker_id",seeker_id).eq("company_id",company_id).eq("state",1);
        if(followingService.getOne(queryWrapper)!=null) {
            return Result.error(ResultCode.SEEKER_COLLECTION_FAIL,false);
        }
        Following following = new Following();
        following.setSeeker_id(seeker_id);
        following.setState(1);
        following.setCompany_id(company_id);
        return Result.success(ResultCode.SEEKER_COLLECTION_SUCCESS,followingService.save(following));
    }

    /**
     * 获取已关注企业列表
     */
    @GetMapping("/getFollowing/{seeker_id}")
    public Result getFollowing(@PathVariable Long seeker_id) {
        QueryWrapper<Following> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seeker_id",seeker_id).eq("state",1);
        List<Following> followings = followingService.list(queryWrapper);
        List<CompanyBriefVO> companyBriefVOS = new LinkedList<>();
        followings.forEach(e -> {
            Long company_id = e.getCompany_id();
            CompanyBriefVO companyBriefVO = BeanUtil.copyProperties(companyService.getById(company_id),CompanyBriefVO.class);
            companyBriefVOS.add(companyBriefVO);
        });
        return Result.success(ResultCode.SEEKER_COLLECTION_SUCCESS,companyBriefVOS);
    }

    /**
     * 撤销关注企业
     */
    @Transactional
    @PutMapping("/cancelFollowing")
    public Result cancelFollowing(@RequestParam Long seeker_id, @RequestParam Long company_id) {
        UpdateWrapper<Following> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("seeker_id",seeker_id).eq("company_id",company_id).eq("state",1);
        updateWrapper.set("state",0);
        return Result.success(ResultCode.SEEKER_COLLECTION_SUCCESS,followingService.update(updateWrapper));
    }

    /**
     * 判断是否已关注企业
     */
    @GetMapping("/hasFollowedCompany")
    public Result hasFollowedCompany(@RequestParam Long seeker_id, @RequestParam Long company_id) {
        QueryWrapper<Following> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seeker_id",seeker_id).eq("company_id",company_id).eq("state",1);
        return Result.success(ResultCode.SEEKER_COLLECTION_SUCCESS,followingService.getOne(queryWrapper)!=null);
    }

    /**
     * 搜索职业
     */
    @GetMapping("/searchJobs")
    public Result searchJobs(@RequestParam String key) {
        QueryWrapper<Job> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("title",key).eq("state",1);
        List<Job> jobs = jobService.list(queryWrapper);
        List<JobHomeVO> jobHomeVOS = new LinkedList<>();
        jobs.forEach(e -> {
            JobHomeVO jobHomeVO = BeanUtil.copyProperties(e,JobHomeVO.class);
            Company company = companyService.getById(jobHomeVO.getCompany_id());
            jobHomeVO.setCompany_icon(company.getCompany_icon());
            jobHomeVO.setCompany_name(company.getCompany_name());
            jobHomeVO.setIndustry_code(company.getIndustry_code());
            jobHomeVO.setSize(company.getSize());
            jobHomeVOS.add(jobHomeVO);
        });
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,jobHomeVOS);
    }

    /**
     * 搜索企业
     */
    @GetMapping("/searchCompanies")
    public Result searchCompanies(@RequestParam String key) {
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("company_name",key).eq("state",1);
        List<Company> companies = companyService.list(queryWrapper);
        List<CompanyBriefVO> companyBriefVOS = new LinkedList<>();
        companies.forEach(e -> {
            Long company_id = e.getCompany_id();
            CompanyBriefVO companyBriefVO = BeanUtil.copyProperties(companyService.getById(company_id),CompanyBriefVO.class);
            companyBriefVOS.add(companyBriefVO);
        });
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,companyBriefVOS);
    }

    /**
     * 按职位代码搜索职业
     */
    @GetMapping("/searchCodeJobs")
    public Result searchCodeJobs(@RequestParam String job_code) {
        QueryWrapper<Job> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("job_code",job_code).eq("state",1);
        List<Job> jobs = jobService.list(queryWrapper);
        List<JobHomeVO> jobHomeVOS = new LinkedList<>();
        jobs.forEach(e -> {
            JobHomeVO jobHomeVO = BeanUtil.copyProperties(e,JobHomeVO.class);
            Company company = companyService.getById(jobHomeVO.getCompany_id());
            jobHomeVO.setCompany_icon(company.getCompany_icon());
            jobHomeVO.setCompany_name(company.getCompany_name());
            jobHomeVO.setIndustry_code(company.getIndustry_code());
            jobHomeVO.setSize(company.getSize());
            jobHomeVOS.add(jobHomeVO);
        });
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,jobHomeVOS);
    }

    /**
     * 投递简历
     */
    @Transactional
    @PostMapping("/submitResume")
    public Result submitResume(@RequestBody ResumeSubmissionDTO submissionDTO) {
        return resumeSubmissionUtil.submitResume(submissionDTO);
    }

    /**
     * 获取简历投递列表
     */
    @GetMapping("/getResumeSubmissions/{seeker_id}")
    public Result getResumeSubmissions(@PathVariable Long seeker_id) {
        return Result.success(ResultCode.SEEKER_GET_SUBMISSIONS_SUCCESS,resumeSubmissionUtil.getResumeSubmissions("seeker_id",seeker_id));
    }

    /**
     * 获取简历投递进展
     */
    @GetMapping("/getResumeSubmissionProgress")
    public Result getResumeSubmissionProgress(@RequestParam Long submission_id) {
        return Result.success(ResultCode.SEEKER_GET_SUCCESS,resumeSubmissionUtil.getResumeSubmissionProgress(submission_id));
    }

}
